@model CleverCMS.Blog.Services.ViewModels.AdminEditPostViewModel
@using CleverCMS.Blog.Data.Extensions
@using CleverCMS.Core.Web.Extensions
@using System.Web.Mvc

@section TitleContent
{
    @((Model != null && Model.Page.Id != 0) ? "Edit Post" : "New Post")
}

@section HeadContent
{
    <script type="text/javascript">
        var tags = [];
        
        $(document).ready(function() {
            showPermalinkForExistingPage();
            $('#Page_Header').blur(function() {
                if (jQuery.trim($('#Page_Header').val()) != '') {
                    saveDraftPage();
                }
            });

            $("#tags").tagsInput({ 'width': '100%', 'margin':'2px' });

            getTagsList();
            
            $("input#tags_tag").autocomplete({
                source: tags
            });

            $("input[name='Page.Created']").datepicker();
            
            $("button[type=submit]").on("click", function () {
                $("html, body").animate({ scrollTop: 0 }, "slow");
            });
            $('#Visible').attr('checked', 'checked');
        });

        function getTagsList() {
            $.ajax({
                url: "@Url.Action("GetTags","Blog")",
                type: "POST",
                async: false,
                success: function (result) {
                    $.each(result, function(i, item) {
                        tags.push(item.Name);
                    });
                }
            });
        }

        function saveDraftPage() {
            if ($('#Page_Id').val() != 0)
                return;
            var title = jQuery.trim($('#Page_Header').val());
            var categoryId = $('#CategoryId > option:selected').val();
            $.post("@Url.Action("CreatePostAlias","Tools", new { area = "" })", { title: title, categoryId: categoryId }, createAliasCallback, "json");
        }

        function createAliasCallback(data, textStatus) {
            if (data) {
                $('#permalink').show();
                updatePage(data);
            }
        }
        
        function updatePage(data) {
            var alias = data.alias;
            var pageId = data.id;
            var url = data.url;
            $('#Page_Id').val(pageId);
            $('#Page_HeaderUrl').val(alias);
            $('#pagePermalink').html(url);
            $('#permalinkUrl').attr('href', url);
            $('#txtNewPageAlias').val(alias);
        }

        function showPermalinkForExistingPage() {
            var alias = $('#Page_HeaderUrl').val();
            if (alias) {
                $('#permalink').show();
            }
                
        }

        function changeAlias() {
            var alias = $('#txtNewPageAlias').val();
            var index = alias.lastIndexOf('-');
            var newAlias = alias.substring(0, index);
            $('#txtNewPageAlias').val(newAlias);
            $('#pageAlias').show();
            $('#changeAliasButtonContainer').hide();
        }

        function updateAlias() {
            var newAliasText = $('#txtNewPageAlias').val();
            var pageId = $('#Page_Id').val();
            $.post("@Url.Action("UpdatePostAlias","Tools", new { area = "" })", { id: pageId, alias: newAliasText }, updateAliasCallback, "json");
        }

        function updateAliasCallback(data, textStatus) {
            if (data) {
                $('#pageAlias').hide();
                $('#changeAliasButtonContainer').show();
                updatePage(data);
            }
        }
    </script>

    <script type="text/javascript">
        $(function() {
            $("#Tags")
                .bind("keypress", function(event) {
                    getTagList(event);

                    if (event.keyCode === $.ui.keyCode.TAB &&
                        $(this).data("autocomplete").menu.active) {
                        event.preventDefault();
                    }
                });
        });

        function split(val) {
            return val.split(/,\s*/);
        }

        function extractLast(term) {
            return split(term).pop();
        }

        function resetAutocomplete(tags) {
            $('#Tags')
                .autocomplete(
                    {
                        minLength: 0,
                        source: function(request, response) {
                            response($.ui.autocomplete.filter(
                                tags, extractLast(request.term)));
                        },
                        focus: function() {
                            return false;
                        },
                        select: function(event, ui) {
                            var terms = split(this.value);
                            terms.pop();
                            terms.push(ui.item.value);
                            terms.push("");
                            this.value = terms.join(", ");
                            return false;
                        }
                    });
        }

        function getTagList(e) {
            var c = String.fromCharCode(e.which);
            var tagsText = $('#Tags').val();
            $.getJSON('/admin/Service/SuggestTag/' + tagsText + c,
                function(json) {
                    var tags = [];
                    $.each(json, function(i, item) {
                        tags.push(item.Name);
                    });
                    resetAutocomplete(tags);
                }
            );
        }

        function successSave(e) {
            if (e.success) {
                $("#failureResult").hide();
                $("#successResult").show().fadeOut(5000);
            } else {
                $("#errortext").html(e.error);
                $("#failureResult").fadeIn(1000);
            }
        }
        function failureSave() {
            $("#failureResult").show().fadeIn(700);
        }
    </script>
    
    <script src="@Url.Content("~/Scripts/ckfinder/ckfinder.js")" type="text/javascript"></script>
}

<div class="widget green">
    <div class="widget-title">
        <h4><i class="icon-reorder"></i> Post</h4>
    </div>
    <div class="widget-body">
        
        <div id="failureResult" class="alert alert-block alert-error" style="display: none">
            <h4 class="alert-heading">Error!</h4>
            <p id="errortext">
            </p>
        </div>

        <div class="alert alert-block alert-success" style="display: none" id="successResult">
            <h4 class="alert-heading">Success!</h4>
            <p>
                Items was successfully saved.
            </p>
        </div>

        @using (Ajax.BeginForm("Edit", "Blog", new AjaxOptions { HttpMethod = "POST", OnFailure = "failureSave", OnSuccess = "successSave" }, new { id = "editEntryForm", @class = "search_form general_form" }))
        {
            
            @Html.HiddenFor(x => x.Page.Id)
            @Html.HiddenFor(x => x.Page.HeaderUrl)
            @Html.HiddenFor(x => x.Page.Modified)
            @Html.HiddenFor(x => x.Page.Visible)
            @Html.HiddenFor(x => x.Page.CategoryId)
            @Html.HiddenFor(x => x.Page.Author)

            <div class="row-fluid">
                <div class="span8">
                    <div class="row-fluid">
                        <div class="span9">
                            <label>Title</label>
                            @Html.ValidationMessageFor(x => x.Page.Header)
                            @Html.TextBoxFor(x => x.Page.Header, new { @style = "width: 100%" })    
                        </div>
                        <div class="span3">
                            <label>Category</label>
                            @Html.DropDownList("CategoryId", Model.Categories, new { @style = "width: 100%" })
                        </div>
                    </div>
            
                    <div id="permalink" style="display: none">
                        <div class="row-fluid">
                            <div class="span1">
                                <label>Permalink</label>
                            </div>
                            <div class="span11">
                                <div class="inputs">
                                    <table>
                                        <tr>
                                            <td>
                                                <span>
                                                    <span>
                                                        <a class="open button" id="permalinkUrl" href="@Url.Action("Index","Blog", new { area = "", id = Html.PostLink(Model.Page)} )" target="_blank">
                                                            <span class="alt_btn">OPEN</span>
                                                        </a>
                                                    </span>
                                                </span>
                                                <span style="margin-left: 10px; text-align: right;">
                                                    @(HttpUtility.UrlDecode(Url.PostSiteUrl().TrimEnd('/')))
                                                </span>
                                                <span id="pagePermalink">@Html.PostLink(Model.Page)</span>
                                                <div id="pageAlias" style="display: none;">
                                                    <table>
                                                        <tr>
                                                            <td style="width: 420px">
                                                                <input type="text" class="text wide" id="txtNewPageAlias" value="@Model.Page.HeaderUrl" />
                                                            </td>
                                                            <td>
                                                                <span class="button send_form_btn">
                                                                    <span>
                                                                        <a href="#" class="button" onclick="updateAlias(); return false;">
                                                                            <span class="alt_btn">SAVE</span>
                                                                        </a>
                                                                    </span>
                                                                </span>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </div>
                                            </td>
                                            <td>
                                                <span id="changeAliasButtonContainer" class="button send_form_btn" >
                                                    <span>
                                                        <a href="#" class="button" onclick="changeAlias(); return false;">
                                                            <span class="alt_btn"> EDIT</span> 
                                                        </a>
                                                    </span>
                                                </span>
                                            </td>
                                        </tr>
                                    </table>
                                </div>  
                            </div>
                        </div>
                    </div>

                    <label style="float: none;">Short Content</label>
                    @Html.TextAreaFor(x => x.Page.ShortContent, new { @style = "width: 100%; height: 200px;", @name = "ShortContent", @id = "ShortContent" })
                    <script type="text/javascript">
                        CKEDITOR.replace('ShortContent',
                            {
                                scayt_autoStartup: false,
                                filebrowserBrowseUrl: "@Url.Content("~/Scripts/ckfinder/ckfinder.html")",
                                filebrowserImageBrowseUrl: "@Url.Content("~/Scripts/ckfinder/ckfinder.html?type=Images")",
                                filebrowserFlashBrowseUrl: "@Url.Content("~/Scripts/ckfinder/ckfinder.html?type=Flash")",
                                filebrowserUploadUrl: "@Url.Content("~/Scripts/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Files")",
                                filebrowserImageUploadUrl: "@Url.Content("~/Scripts/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Images")",
                                filebrowserFlashUploadUrl: "@Url.Content("~/Scripts/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Flash")",
                                filebrowserWindowWidth: "1000",
                                filebrowserWindowHeight: "700"
                            });
                    </script>
            
                    <label style="float: none;">Content</label>
                    @Html.TextAreaFor(x => x.Page.Content, new { @style = "width: 100%; height: 200px;", @name = "Content", @id = "Content" })
                    <script type="text/javascript">
                        CKEDITOR.replace('Content',
                            {
                                scayt_autoStartup: false,
                                filebrowserBrowseUrl: "@Url.Content("~/Scripts/ckfinder/ckfinder.html")",
                                filebrowserImageBrowseUrl: "@Url.Content("~/Scripts/ckfinder/ckfinder.html?type=Images")",
                                filebrowserFlashBrowseUrl: "@Url.Content("~/Scripts/ckfinder/ckfinder.html?type=Flash")",
                                filebrowserUploadUrl: "@Url.Content("~/Scripts/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Files")",
                                filebrowserImageUploadUrl: "@Url.Content("~/Scripts/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Images")",
                                filebrowserFlashUploadUrl: "@Url.Content("~/Scripts/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Flash")",
                                filebrowserWindowWidth: "1000",
                                filebrowserWindowHeight: "700"
                            });
                    </script>
            
                    <div class="row-fluid" style="margin: 10px 0px;">
                        <div class="span6">
                            <label>Tags</label>
                            @Html.TextBox("Tags", Model.Page.BlogEntryTags.ToTagString(), new { @style = "width: 100%", @id = "tags" })   
                        </div>
                        <div class="span6">
                            <label>Meta Title</label>
                            @Html.TextAreaFor(x => x.Page.SeoTitle, new { @style = "width: 100%; height: 100px" })      
                        </div>
                    </div>
                    
                    <div class="row-fluid">
                        <div class="span6">
                            <label>Meta Keywords</label>
                            @Html.TextAreaFor(x => x.Page.MetaKeywords, new { @style = "width: 100%" })   
                        </div>
                        <div class="span6">
                            <label>Meta Description</label>
                            @Html.TextAreaFor(x => x.Page.MetaDescription, new { @style = "width: 100%" })      
                        </div>     
                    </div>
                        
                    <div id="footer-buttons" class="row-fluid" >
                        <div class="pull-right">
                            <div class="submit_link">
                                <button type="submit" class="btn btn-success" name="save_post"><i class="icon-ok icon-white"></i> Publish</button>
                                <button class="btn btn-inverse" onclick="resetFields(this); return false;"><i class="icon-refresh icon-white"></i> Reset</button>
                                <button class="btn btn-inverse" onclick="history.back()"><i class="icon-ban-circle icon-white"></i> Back</button> 
                            </div>                      
                        </div>
                        @Html.CheckBoxFor(x => x.Visible, new { @class = "page-statuses pull-right", @style = "margin-right: 20px; margin-left: 5px;" })
                        <label class="pull-right">Visible</label>
                        @Html.CheckBoxFor(x => x.ShowRating, new { @class = "page-statuses pull-right", @style = "margin-right: 20px; margin-left: 5px;"})
                        <label  class="pull-right">Show rating</label>
                        @Html.TextBox("Page.Created", Model.Page.Created.ToString("MM/dd/yyyy"), new { @class = "pull-right", @style = "margin-right: 20px; margin-left: 5px;" })
                        <label  class="pull-right">Date</label>
                    </div>
                </div>
            </div>
        }
    </div>
</div>

<style type="text/css">
    #footer-buttons > label {padding-top: 5px; height: 20px;}
    #footer-buttons > input[type='checkbox'] {margin-top: 5px;}
</style>